var app = require('../app');
var r = new Uploader({
    target: '/api/upload/chunk',
    chunkSize: 5 * 1024 * 1024,           // 分片大小 5Mb 
    testChunks: true,
    forceChunkSize: true,
    checkChunkUploadedByResponse: function (chunk, message) {
        console.log(chunk, message);
        var objMessage = {}
        try {
            objMessage = JSON.parse(message)
        } catch (e) { }
        // fake response
        // objMessage.uploaded_chunks = [2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 17, 20, 21]
        // check the chunk is uploaded
        return (objMessage.uploaded_chunks || []).indexOf(chunk.offset + 1) >= 0
    }
});
// simple-uploader.js isn't supported, fall back on a different method
if (!r.support) {
    $('.uploader-error').show();
    return;
}
// Show a place for dropping/selecting files
$('.uploader-drop').show();
r.assignDrop($('.uploader-drop')[0]);
r.assignBrowse($('.uploader-browse')[0]);
r.assignBrowse($('.uploader-browse-folder')[0], true);
r.assignBrowse($('.uploader-browse-image')[0], false, false, { accept: 'image/*' });

// Handle file add event
r.on('filesAdded', function (files, fileList) {     // 添加单个文件
    // Show progress bar  展示进度条
    $('.uploader-progress, .uploader-list').show();
    fileList.forEach(function (file) {
        
        // 单个文件上传的 dom
        var $self = file.$el = $(
            '<li class="uploader-file">' +
            '上传中 <span class="uploader-file-name"></span> | ' +
            '<span class="uploader-file-size"></span> | ' +
            '<span class="uploader-file-progress"></span> ' +
            '<span class="uploader-file-md5" style="font-size: 24px; color: #f00;"></span> ' +
            '<span class="uploader-file-pause">' +
            ' <img src="/images/mediation/index/upload/pause.png" title="Pause upload">' +
            '</span>' +
            '<span class="uploader-file-resume">' +
            ' <img src="/images/mediation/index/upload/resume.png" title="Resume upload">' +
            '</span>' +
            '<span class="uploader-file-cancel">' +
            ' <img src="/images/mediation/index/upload/cancel.png" title="Cancel upload">' +
            '</span>' +
            '</li>'
            );
        
        $self.find('.uploader-file-name').text(file.name);  // 文件名
        $self.find('.uploader-file-size').text(file.getFormatSize());   // 文件大小
        
        // 暂停
        $self.find('.uploader-file-pause').on('click', function () {
            file.pause();   // 暂停 file 上传
            
            // 展示改变
            $self.find('.uploader-file-pause').hide(); 
            $self.find('.uploader-file-resume').show();
        });
        
        // 重新开始
        $self.find('.uploader-file-resume').on('click', function () {
            file.resume();      // 重新开始 上传
            
            // 展示改变
            $self.find('.uploader-file-pause').show();
            $self.find('.uploader-file-resume').hide();
        });
        
        // 取消
        $self.find('.uploader-file-cancel').on('click', function () {
            file.cancel();      // 取消上传
            $self.remove();     // 删除 DOM
        });
        
        $('.uploader-list').append($self);

        // computeMD5(file, $self);
    });
});
    
// 和 filesAdded 类似，但是是文件已经加入到上传列表中，一般用来开始整个的上传
r.on('filesSubmitted', function (files, fileList) {
    window.r.upload();
});

// 已经开始上传了
r.on('uploadStart', function () {
    // Show pause, hide resume
    $('.uploader-progress .progress-resume-link').hide();
    $('.uploader-progress .progress-pause-link').show();
});

// 一个文件在上传中
r.on('fileProgress', function (rootFile, file) {
    // Handle progress for both the file and the overall upload
    rootFile.$el.find('.uploader-file-progress')
    .html(Math.floor(rootFile.progress() * 100) + '% '
    + '速度：' + Uploader.utils.formatSize(rootFile.averageSpeed) + '/s '
    + '剩余：' + secondsToStr(rootFile.timeRemaining()) );
    $('.progress-bar').css({ width: Math.floor(r.progress() * 100) + '%' });
});

// 一个根文件（文件夹）成功上传完成
r.on('fileComplete', function (rooFile) {
    var $self = rooFile.$el
    // Reflect that the file upload has completed
    $self.find('.uploader-file-progress').text('（完成）');
    $self.find('.uploader-file-pause, .uploader-file-resume').remove();
});

// 上传完毕
r.on('complete', function () {
    // Hide pause/resume when the upload has completed
    // 当文件上传完成时 隐藏 开始、暂停 按钮
    $('.uploader-progress .progress-resume-link, .uploader-progress .progress-pause-link').hide();
});

// 上传过程中出错了
r.on('fileError', function (rootFile, file, message) {
    rootFile.$el.find('.uploader-file-progress').html('(file could not be uploaded: ' + message + ')')
});

// 所有的事件
r.on('catchAll', function () {
    // console.log.apply(console, arguments);
});

window.r = {
    pause: function () {
        r.pause();
        // Show resume, hide pause
        $('.uploader-file-resume').show();
        $('.uploader-file-pause').hide();
        $('.uploader-progress .progress-resume-link').show();
        $('.uploader-progress .progress-pause-link').hide();
    },
    cancel: function () {
        r.cancel();
        $('.uploader-file').remove();
    },
    upload: function () {
        $('.uploader-file-pause').show();
        $('.uploader-file-resume').hide();
        r.resume();
    },
    uploader: r
};

    
// 秒换算成  天/时/分/秒
function secondsToStr(temp) {
    var timeStr = "",
    
    dayBase = 24 * 60 * 60 ,
    hourBase = 60 * 60 ,
    minuteBase = 60 ,
    secondBase = 1,
    
    day = Math.floor(temp / dayBase),
    hour = Math.floor(temp % dayBase / hourBase),
    minute = Math.floor(temp % dayBase % hourBase / minuteBase),
    second = Math.floor(temp % dayBase % hourBase % minuteBase / secondBase);
    
    timeStr = (day ? day + "天 " : "")
    + (hour ? hour + "时 " : "")
    + (minute ? minute + "分 " : "")
    + (second ? second + "秒 " : "");
    
    timeStr = timeStr ? timeStr : "0秒";
    return timeStr;
}

// 计算MD5值
function computeMD5(file, el) {
    var that = this;
    isUploaded_zip = false; // 这个文件是否已经上传成功过
    notUploadedChunkNumbers_zip = []; // 未成功的chunkNumber
    var fileReader = new FileReader();
    let time = new Date().getTime();
    let md5 = '';

    console.log("开始读取");
    el.find('uploader-file-md5').html("文件读取中");
    file.pause();

    fileReader.readAsArrayBuffer(file.file);
    fileReader.onload = function(e) {
        if (file.size != e.target.result.byteLength) {
            this.error('Browser reported success but could not read the file until the end.');
            console.log("文件读取失败");
            return false;
        }

        el.find('uploader-file-md5').html("校验MD5中");
        md5 = SparkMD5.ArrayBuffer.hash(e.target.result, false);
        console.log(`MD5计算完毕：${file.id}
        ${file.name}
        MD5：${md5}
        用时：${new Date().getTime() - time} ms`);
        file.uniqueIdentifier = md5;

        el.find('uploader-file-md5').html("上传中");
        file.resume();
        el.find('.uploader-file-pause').show();
        el.find('.uploader-file-resume').hide();

        // if (md5 != "") {
        //     checkFileMd5({
        //         "md5": md5
        //     }).then(res =>{
        //         if (res.status == 200) {
        //             if (res.data.code == 100) { // 上传成功过
        //                 isUploaded_zip = true;
        //                 that.$message({
        //                     message: "该文件已经上传成功过了，不能再上传了哦。",
        //                     type: 'success'
        //                 });
        //                 file.cancel();
        //             } else if (res.data.code == 101) { // 该文件没有上传过
        //                 isUploaded_zip = false;
        //                 file.resume();
        //             } else if (res.data.code == 102) { // 如果102 ，返回未上传过的 chunkNumber 数组
        //                 isUploaded_zip = false;
        //                 notUploadedChunkNumbers_zip = res.data.data;
        //                 file.resume();
        //             } else {}
        //         } else {}
        //     })
        // }

        // 添加额外的参数
        // this.uploader.opts.query = {
        //   ...that.params
        // }
    };
    fileReader.onerror = function() {
        this.error('generater md5 时FileReader异步读取文件出错了，FileReader onerror was triggered, maybe the browser aborted due to high memory usage.');
        return false;
    };
}
